"""
Application Configuration
应用配置管理 - 无Redis依赖
"""

from typing import List, Optional
from pydantic import validator, Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class DatabaseSettings(BaseSettings):
    """数据库配置"""

    url: str = Field(
        default="postgresql+asyncpg://media_user:password@localhost:5432/media_create_db",
        description="PostgreSQL数据库连接URL",
    )
    pool_size: int = Field(default=20, description="连接池大小")
    max_overflow: int = Field(default=40, description="连接池最大溢出")
    pool_timeout: int = Field(default=30, description="连接池超时时间（秒）")

    @validator("pool_size", "max_overflow", "pool_timeout")
    def validate_positive(cls, v):
        if v <= 0:
            raise ValueError("必须为正数")
        return v


class AIProviderSettings(BaseSettings):
    """AI模型提供商配置"""

    default_provider: str = Field(default="doubao", description="默认AI提供商")

    # 豆包配置
    ark_api_key: Optional[str] = Field(default=None, description="豆包API密钥")
    ark_base_url: str = Field(
        default="https://ark.cn-beijing.volces.com/api/v3", description="豆包API基础URL"
    )

    # 阿里云配置
    ali_api_key: Optional[str] = Field(default=None, description="阿里云API密钥")
    ali_base_url: str = Field(
        default="https://dashscope.aliyuncs.com/api/v1", description="阿里云API基础URL"
    )

    # OpenAI配置
    openai_api_key: Optional[str] = Field(default=None, description="OpenAI API密钥")


class SecuritySettings(BaseSettings):
    """安全配置"""

    secret_key: str = Field(description="应用密钥，用于JWT等")
    jwt_algorithm: str = Field(default="HS256", description="JWT算法")
    jwt_expiration_hours: int = Field(default=24, description="JWT过期时间（小时）")

    password_min_length: int = Field(default=8, description="密码最小长度")
    password_require_uppercase: bool = Field(
        default=True, description="密码需要大写字母"
    )
    password_require_lowercase: bool = Field(
        default=True, description="密码需要小写字母"
    )
    password_require_numbers: bool = Field(default=True, description="密码需要数字")
    password_require_special_chars: bool = Field(
        default=True, description="密码需要特殊字符"
    )

    max_failed_login_attempts: int = Field(default=5, description="最大登录失败次数")
    account_lockout_duration_minutes: int = Field(
        default=60, description="账户锁定时间（分钟）"
    )

    cors_origins_raw: str = Field(
        default="http://localhost:3000", description="CORS允许的源(逗号分隔)"
    )
    cors_allow_credentials: bool = Field(default=True, description="CORS允许凭据")

    @property
    def cors_origins(self) -> List[str]:
        """解析CORS源列表"""
        if not self.cors_origins_raw:
            return ["http://localhost:3000"]
        return [origin.strip() for origin in self.cors_origins_raw.split(",") if origin.strip()]

    @validator("secret_key")
    def validate_secret_key(cls, v):
        """验证密钥"""
        if not v or len(v) < 32:
            raise ValueError("密钥长度必须至少32个字符")
        return v


class FileStorageSettings(BaseSettings):
    """文件存储配置"""

    upload_dir: str = Field(default="uploads", description="上传文件目录")
    max_upload_size_mb: int = Field(default=100, description="最大上传文件大小（MB）")
    allowed_extensions: str = Field(
        default="png,jpg,jpeg,gif,webp,mp4,mp3,wav", description="允许的文件扩展名"
    )
    content_storage_path: str = Field(
        default="generated_content", description="生成内容存储路径"
    )
    content_base_url: str = Field(
        default="http://localhost:8039/content", description="内容基础URL"
    )
    temp_file_lifetime: int = Field(default=24, description="临时文件生命周期（小时）")


class UserLimitSettings(BaseSettings):
    """用户限制配置"""

    guest_daily_generation_limit: int = Field(default=5, description="访客每日生成限制")
    guest_storage_limit_mb: int = Field(default=100, description="访客存储限制（MB）")
    guest_content_lifetime_hours: int = Field(
        default=24, description="访客内容生命周期（小时）"
    )

    registered_daily_generation_limit: int = Field(
        default=50, description="注册用户每日生成限制"
    )
    registered_storage_limit_mb: int = Field(
        default=1024, description="注册用户存储限制（MB）"
    )

    max_concurrent_tasks_per_user: int = Field(
        default=3, description="单个用户最大并发任务数"
    )
    max_concurrent_tasks_system: int = Field(
        default=100, description="系统最大并发任务数"
    )


class ContentGenerationSettings(BaseSettings):
    """内容生成配置"""

    generation_timeout_seconds: int = Field(
        default=300, description="生成任务超时时间（秒）"
    )
    quality_score_threshold: float = Field(default=6.0, description="质量评分阈值")
    default_image_size: str = Field(default="1K", description="默认图像尺寸")
    default_video_duration: int = Field(default=5, description="默认视频时长（秒）")
    default_audio_duration: int = Field(default=30, description="默认音频时长（秒）")
    enable_content_moderation: bool = Field(default=True, description="启用内容审核")
    nsfw_filter_sensitivity: float = Field(default=0.8, description="NSFW过滤器敏感度")


class TaskQueueSettings(BaseSettings):
    """任务队列配置"""

    max_workers: int = Field(default=5, description="最大工作协程数")
    max_tasks: int = Field(default=1000, description="最大任务数")
    cleanup_interval_hours: int = Field(default=24, description="清理间隔（小时）")
    task_timeout_seconds: int = Field(default=300, description="任务超时时间（秒）")


class LoggingSettings(BaseSettings):
    """日志配置"""

    level: str = Field(default="INFO", description="日志级别")
    file_path: str = Field(default="logs/media-create.log", description="日志文件路径")
    max_size_mb: int = Field(default=100, description="日志文件最大大小（MB）")
    backup_count: int = Field(default=5, description="日志备份数量")
    enable_structured_logging: bool = Field(default=True, description="启用结构化日志")


class ApplicationSettings(BaseSettings):
    """应用配置"""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        env_nested_delimiter="__",
    )

    # 基础配置
    app_name: str = Field(default="media-create-gui", description="应用名称")
    app_version: str = Field(default="1.0.0", description="应用版本")
    app_env: str = Field(default="development", description="应用环境")

    # 服务器配置 - 默认绑定到localhost以提高安全性
    host: str = Field(default="127.0.0.1", description="服务器主机 (生产环境建议设置为具体IP)")
    port: int = Field(default=8039, description="服务器端口")
    debug: bool = Field(default=True, description="调试模式")

    # 子配置
    database: DatabaseSettings = Field(default_factory=DatabaseSettings)
    ai_provider: AIProviderSettings = Field(default_factory=AIProviderSettings)
    security: SecuritySettings = Field(default_factory=SecuritySettings)
    file_storage: FileStorageSettings = Field(default_factory=FileStorageSettings)
    user_limit: UserLimitSettings = Field(default_factory=UserLimitSettings)
    content_generation: ContentGenerationSettings = Field(
        default_factory=ContentGenerationSettings
    )
    task_queue: TaskQueueSettings = Field(default_factory=TaskQueueSettings)
    logging: LoggingSettings = Field(default_factory=LoggingSettings)

    @validator("app_env")
    def validate_app_env(cls, v):
        valid_envs = ["development", "testing", "production"]
        if v not in valid_envs:
            raise ValueError(f"环境必须是 {valid_envs} 之一")
        return v

    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self.app_env == "development"

    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return self.app_env == "production"

    @property
    def is_testing(self) -> bool:
        """是否为测试环境"""
        return self.app_env == "testing"


# 全局配置实例
settings = ApplicationSettings()

# 导出配置
__all__ = ["settings", "ApplicationSettings"]